<template>
  <view class="branch-story-page">
    <!-- 剧情选择界面 -->
    <view v-if="!currentStory" class="story-selection">
      <text class="page-title">信任分支剧情</text>
      <text class="page-subtitle">体验不同的信任选择，塑造你的信任故事</text>
      
      <!-- 信任状态概览 -->
      <view class="trust-overview">
        <view class="overview-item">
          <text class="overview-label">当前信任值</text>
          <text class="overview-value">{{ currentTrustValue }}</text>
        </view>
        <view class="overview-item">
          <text class="overview-label">信任等级</text>
          <text class="overview-value" :class="getTrustLevelClass()">{{ getTrustLevelText() }}</text>
        </view>
        <view class="overview-item">
          <text class="overview-label">完成剧情</text>
          <text class="overview-value">{{ completedStories }}</text>
        </view>
      </view>
      
      <!-- 剧情推荐 -->
      <view class="story-recommendations" v-if="recommendations.length > 0">
        <text class="section-title">推荐剧情</text>
        <view class="recommendations-list">
          <view 
            class="recommendation-item" 
            v-for="rec in recommendations" 
            :key="rec.storyId"
            :class="rec.priority"
            @click="startRecommendedStory(rec)"
          >
            <view class="rec-header">
              <text class="rec-icon">📖</text>
              <text class="rec-title">{{ getStoryTitle(rec.storyId) }}</text>
              <view class="rec-priority" :class="rec.priority">
                <text class="priority-text">{{ getPriorityText(rec.priority) }}</text>
              </view>
            </view>
            <text class="rec-reason">{{ rec.reason }}</text>
          </view>
        </view>
      </view>
      
      <!-- 所有剧情列表 -->
      <view class="all-stories">
        <text class="section-title">所有剧情</text>
        <view class="stories-list">
          <view 
            class="story-item" 
            v-for="story in allStories" 
            :key="story.id"
            @click="startStory(story.id)"
          >
            <view class="story-header">
              <text class="story-icon">📚</text>
              <text class="story-title">{{ story.title }}</text>
              <view class="story-status" :class="getStoryStatusClass(story.id)">
                <text class="status-text">{{ getStoryStatusText(story.id) }}</text>
              </view>
            </view>
            <text class="story-subtitle">{{ story.subtitle }}</text>
            <view class="story-stats">
              <text class="stat-item">步骤: {{ story.steps.length }}</text>
              <text class="stat-item">难度: {{ getStoryDifficulty(story.id) }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 剧情历史 -->
      <view class="story-history" v-if="storyHistory.length > 0">
        <text class="section-title">剧情历史</text>
        <view class="history-list">
          <view 
            class="history-item" 
            v-for="(entry, index) in recentHistory" 
            :key="index"
            @click="viewHistoryDetail(entry)"
          >
            <view class="history-header">
              <text class="history-title">{{ getStoryTitle(entry.storyId) }}</text>
              <text class="history-time">{{ formatTime(entry.startTime) }}</text>
            </view>
            <view class="history-result" v-if="entry.result">
              <text class="result-trust">最终信任值: {{ entry.result.finalTrustValue }}</text>
              <text class="result-choices">选择次数: {{ entry.result.totalChoices }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 剧情进行界面 -->
    <view v-else class="story-progress">
      <TrustBranchStory 
        :storyData="currentStory"
        :initialTrustValue="currentTrustValue"
        @branch-selected="handleBranchSelected"
        @branch-result="handleBranchResult"
        @story-complete="handleStoryComplete"
        @story-restart="handleStoryRestart"
      />
    </view>
    
    <!-- 剧情结果详情 -->
    <view v-if="showResultDetail" class="result-detail-modal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">剧情结果详情</text>
          <button class="close-btn" @click="closeResultDetail">×</button>
        </view>
        
        <view class="result-summary">
          <text class="summary-title">{{ resultDetail.storyTitle }}</text>
          <view class="summary-stats">
            <view class="stat-row">
              <text class="stat-label">最终信任值:</text>
              <text class="stat-value">{{ resultDetail.finalTrustValue }}</text>
            </view>
            <view class="stat-row">
              <text class="stat-label">信任变化:</text>
              <text class="stat-value" :class="getTrustChangeClass(resultDetail.trustChange)">
                {{ getTrustChangeText(resultDetail.trustChange) }}
              </text>
            </view>
            <view class="stat-row">
              <text class="stat-label">选择次数:</text>
              <text class="stat-value">{{ resultDetail.totalChoices }}</text>
            </view>
            <view class="stat-row">
              <text class="stat-label">用时:</text>
              <text class="stat-value">{{ formatDuration(resultDetail.duration) }}</text>
            </view>
          </view>
        </view>
        
        <view class="choice-history">
          <text class="history-title">选择历史</text>
          <view class="choices-list">
            <view 
              class="choice-item" 
              v-for="(choice, index) in resultDetail.choices" 
              :key="index"
            >
              <text class="choice-step">步骤 {{ index + 1 }}</text>
              <text class="choice-branch">{{ getBranchName(choice.stepId, choice.branchId) }}</text>
              <text class="choice-impact" :class="getTrustChangeClass(choice.trustChange)">
                {{ getTrustChangeText(choice.trustChange) }}
              </text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import TrustBranchStory from '@/pages/game/trust-fall/components/trust/TrustBranchStory.vue'
import trustBranchManager from '@/utils/trust-branch-manager.js'
import trustCardManager from '@/utils/trust-card-manager.js'

export default {
  name: 'BranchStoryPage',
  components: {
    TrustBranchStory
  },
  
  data() {
    return {
      currentStory: null,
      currentTrustValue: 50,
      allStories: [],
      recommendations: [],
      storyHistory: [],
      showResultDetail: false,
      resultDetail: {}
    }
  },
  
  computed: {
    completedStories() {
      return this.storyHistory.filter(entry => entry.result).length
    },
    
    recentHistory() {
      return this.storyHistory.slice(0, 5) // 显示最近5个
    }
  },
  
  onLoad() {
    this.initializePage()
  },
  
  methods: {
    // 初始化页面
    initializePage() {
      // 加载信任值
      this.loadCurrentTrustValue()
      
      // 加载剧情数据
      trustBranchManager.loadStoryData()
      
      // 获取所有剧情
      this.allStories = trustBranchManager.getAllStoryTemplates()
      
      // 获取历史记录
      this.storyHistory = trustBranchManager.getStoryHistory()
      
      // 生成推荐
      this.generateRecommendations()
    },
    
    // 加载当前信任值
    loadCurrentTrustValue() {
      // 从信任卡牌管理器获取平均信任值
      const cards = trustCardManager.getAllCards()
      if (cards.length > 0) {
        const totalTrust = cards.reduce((sum, card) => sum + card.trustValue, 0)
        this.currentTrustValue = Math.round(totalTrust / cards.length)
      } else {
        this.currentTrustValue = 50 // 默认值
      }
    },
    
    // 生成推荐
    generateRecommendations() {
      this.recommendations = trustBranchManager.generateStoryRecommendations(this.currentTrustValue)
    },
    
    // 开始剧情
    startStory(storyId) {
      this.currentStory = trustBranchManager.startStory(storyId, this.currentTrustValue)
      if (this.currentStory) {
        uni.showToast({
          title: '剧情开始',
          icon: 'success'
        })
      }
    },
    
    // 开始推荐剧情
    startRecommendedStory(recommendation) {
      this.startStory(recommendation.storyId)
    },
    
    // 处理分支选择
    handleBranchSelected(event) {
      console.log('Branch selected:', event)
    },
    
    // 处理分支结果
    handleBranchResult(event) {
      console.log('Branch result:', event)
      
      // 记录选择
      trustBranchManager.recordChoice(
        event.step,
        event.branch.id,
        event.trustChange
      )
      
      // 更新信任值
      this.currentTrustValue = event.newTrustValue
      
      // 更新信任卡牌
      this.updateTrustCards(event.trustChange)
    },
    
    // 更新信任卡牌
    updateTrustCards(trustChange) {
      const cards = trustCardManager.getAllCards()
      cards.forEach(card => {
        const newTrustValue = Math.max(0, Math.min(100, card.trustValue + trustChange))
        trustCardManager.updateCardTrust(card.id, newTrustValue)
      })
    },
    
    // 处理剧情完成
    handleStoryComplete(event) {
      const result = trustBranchManager.completeStory()
      if (result) {
        // 保存数据
        trustBranchManager.saveStoryData()
        
        // 更新历史记录
        this.storyHistory = trustBranchManager.getStoryHistory()
        
        // 显示结果
        this.showStoryResult(result)
      }
      
      this.currentStory = null
    },
    
    // 处理剧情重启
    handleStoryRestart() {
      this.currentStory = null
      this.initializePage()
    },
    
    // 显示剧情结果
    showStoryResult(result) {
      this.resultDetail = {
        storyTitle: this.getStoryTitle(result.storyId),
        finalTrustValue: result.finalTrustValue,
        trustChange: result.finalTrustValue - this.currentTrustValue,
        totalChoices: result.totalChoices,
        duration: result.duration,
        choices: result.choices
      }
      
      this.showResultDetail = true
      
      // 更新当前信任值
      this.currentTrustValue = result.finalTrustValue
    },
    
    // 关闭结果详情
    closeResultDetail() {
      this.showResultDetail = false
    },
    
    // 查看历史详情
    viewHistoryDetail(entry) {
      if (entry.result) {
        this.resultDetail = {
          storyTitle: this.getStoryTitle(entry.storyId),
          finalTrustValue: entry.result.finalTrustValue,
          trustChange: entry.result.finalTrustValue - 50, // 假设初始值为50
          totalChoices: entry.result.totalChoices,
          duration: entry.result.duration,
          choices: entry.result.choices
        }
        this.showResultDetail = true
      }
    },
    
    // 获取剧情标题
    getStoryTitle(storyId) {
      const story = this.allStories.find(s => s.id === storyId)
      return story ? story.title : '未知剧情'
    },
    
    // 获取信任等级
    getTrustLevel() {
      if (this.currentTrustValue >= 80) return 'high'
      if (this.currentTrustValue >= 50) return 'medium'
      if (this.currentTrustValue >= 20) return 'low'
      return 'broken'
    },
    
    // 获取信任等级文本
    getTrustLevelText() {
      const levels = {
        high: '高度信任',
        medium: '一般信任',
        low: '低度信任',
        broken: '信任破裂'
      }
      return levels[this.getTrustLevel()] || '未知'
    },
    
    // 获取信任等级样式类
    getTrustLevelClass() {
      return `trust-${this.getTrustLevel()}`
    },
    
    // 获取剧情状态
    getStoryStatusClass(storyId) {
      const hasCompleted = this.storyHistory.some(entry => 
        entry.storyId === storyId && entry.result
      )
      return hasCompleted ? 'completed' : 'available'
    },
    
    // 获取剧情状态文本
    getStoryStatusText(storyId) {
      const hasCompleted = this.storyHistory.some(entry => 
        entry.storyId === storyId && entry.result
      )
      return hasCompleted ? '已完成' : '可开始'
    },
    
    // 获取剧情难度
    getStoryDifficulty(storyId) {
      const difficulties = {
        'trust-building': '简单',
        'trust-crisis': '中等',
        'trust-legacy': '困难'
      }
      return difficulties[storyId] || '未知'
    },
    
    // 获取优先级文本
    getPriorityText(priority) {
      const texts = {
        high: '高优先级',
        medium: '中优先级',
        low: '低优先级'
      }
      return texts[priority] || '未知'
    },
    
    // 获取信任变化样式类
    getTrustChangeClass(change) {
      if (change > 0) return 'positive'
      if (change < 0) return 'negative'
      return 'neutral'
    },
    
    // 获取信任变化文本
    getTrustChangeText(change) {
      if (change > 0) return `+${change}`
      if (change < 0) return `${change}`
      return '0'
    },
    
    // 获取分支名称
    getBranchName(stepId, branchId) {
      // 这里应该根据stepId和branchId查找对应的分支名称
      // 简化实现
      return `分支 ${branchId}`
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp)
      return date.toLocaleString()
    },
    
    // 格式化时长
    formatDuration(duration) {
      const minutes = Math.floor(duration / 60000)
      const seconds = Math.floor((duration % 60000) / 1000)
      return `${minutes}分${seconds}秒`
    }
  }
}
</script>

<style scoped>
.branch-story-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20rpx;
  color: white;
}

/* 页面标题 */
.page-title {
  font-size: 48rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 12rpx;
  display: block;
  text-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.2);
}

.page-subtitle {
  font-size: 24rpx;
  text-align: center;
  opacity: 0.8;
  margin-bottom: 40rpx;
  display: block;
}

/* 信任概览 */
.trust-overview {
  display: flex;
  gap: 16rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 30rpx;
  backdrop-filter: blur(10rpx);
}

.overview-item {
  flex: 1;
  text-align: center;
}

.overview-label {
  font-size: 20rpx;
  opacity: 0.8;
  display: block;
  margin-bottom: 8rpx;
}

.overview-value {
  font-size: 28rpx;
  font-weight: bold;
  color: white;
}

.overview-value.trust-high {
  color: #4caf50;
}

.overview-value.trust-medium {
  color: #ff9800;
}

.overview-value.trust-low {
  color: #ff5722;
}

.overview-value.trust-broken {
  color: #f44336;
}

/* 章节标题 */
.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
  text-align: center;
}

/* 推荐剧情 */
.story-recommendations {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.1);
}

.recommendations-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.recommendation-item {
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  padding: 20rpx;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
}

.recommendation-item.high {
  border-color: #4caf50;
  background: rgba(76, 175, 80, 0.05);
}

.recommendation-item.medium {
  border-color: #ff9800;
  background: rgba(255, 152, 0, 0.05);
}

.recommendation-item.low {
  border-color: #9e9e9e;
  background: rgba(158, 158, 158, 0.05);
}

.recommendation-item:hover {
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.rec-header {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.rec-icon {
  font-size: 24rpx;
  margin-right: 12rpx;
}

.rec-title {
  flex: 1;
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
}

.rec-priority {
  padding: 4rpx 8rpx;
  border-radius: 6rpx;
  font-size: 16rpx;
  font-weight: bold;
}

.rec-priority.high {
  background: #e8f5e8;
  color: #4caf50;
}

.rec-priority.medium {
  background: #fff3e0;
  color: #ff9800;
}

.rec-priority.low {
  background: #f5f5f5;
  color: #9e9e9e;
}

.priority-text {
  font-size: 14rpx;
}

.rec-reason {
  font-size: 20rpx;
  color: #666;
  line-height: 1.4;
}

/* 所有剧情 */
.all-stories {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.1);
}

.stories-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.story-item {
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  padding: 20rpx;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
}

.story-item:hover {
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.story-header {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.story-icon {
  font-size: 24rpx;
  margin-right: 12rpx;
}

.story-title {
  flex: 1;
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
}

.story-status {
  padding: 4rpx 8rpx;
  border-radius: 6rpx;
  font-size: 16rpx;
  font-weight: bold;
}

.story-status.completed {
  background: #e8f5e8;
  color: #4caf50;
}

.story-status.available {
  background: #e3f2fd;
  color: #2196f3;
}

.status-text {
  font-size: 14rpx;
}

.story-subtitle {
  font-size: 20rpx;
  color: #666;
  margin-bottom: 12rpx;
  display: block;
}

.story-stats {
  display: flex;
  gap: 16rpx;
}

.stat-item {
  font-size: 18rpx;
  color: #999;
}

/* 剧情历史 */
.story-history {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.1);
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.history-item {
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 16rpx;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f8f9fa;
}

.history-item:hover {
  background: #e9ecef;
  transform: translateX(4rpx);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.history-title {
  font-size: 22rpx;
  font-weight: bold;
  color: #333;
}

.history-time {
  font-size: 18rpx;
  color: #999;
}

.history-result {
  display: flex;
  gap: 16rpx;
}

.result-trust,
.result-choices {
  font-size: 18rpx;
  color: #666;
}

/* 结果详情模态框 */
.result-detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  max-width: 600rpx;
  max-height: 80vh;
  overflow-y: auto;
  color: #333;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  border-bottom: 1rpx solid #e0e0e0;
  padding-bottom: 16rpx;
}

.modal-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background: #f5f5f5;
  color: #666;
  font-size: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.result-summary {
  margin-bottom: 24rpx;
}

.summary-title {
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 16rpx;
  text-align: center;
}

.summary-stats {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-label {
  font-size: 20rpx;
  color: #666;
}

.stat-value {
  font-size: 20rpx;
  font-weight: bold;
  color: #333;
}

.stat-value.positive {
  color: #4caf50;
}

.stat-value.negative {
  color: #f44336;
}

.stat-value.neutral {
  color: #666;
}

.choice-history {
  border-top: 1rpx solid #e0e0e0;
  padding-top: 20rpx;
}

.history-title {
  font-size: 22rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 16rpx;
}

.choices-list {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.choice-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding: 8rpx 12rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
}

.choice-step {
  font-size: 18rpx;
  color: #666;
  min-width: 80rpx;
}

.choice-branch {
  flex: 1;
  font-size: 18rpx;
  color: #333;
}

.choice-impact {
  font-size: 18rpx;
  font-weight: bold;
}

.choice-impact.positive {
  color: #4caf50;
}

.choice-impact.negative {
  color: #f44336;
}

.choice-impact.neutral {
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768rpx) {
  .branch-story-page {
    padding: 16rpx;
  }
  
  .trust-overview {
    flex-direction: column;
    gap: 12rpx;
  }
  
  .story-recommendations,
  .all-stories,
  .story-history {
    padding: 24rpx;
  }
  
  .modal-content {
    margin: 20rpx;
    max-width: calc(100% - 40rpx);
  }
}
</style>

